
package com.example.sistemacompras;

import com.example.sistemacompras.db.DatabaseHandler;
import com.example.sistemacompras.entity.Product;
import com.example.sistemacompras.utils.Utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ManageProductActivity extends Activity {

    private EditText nameEdit;

    private EditText descEdit;

    private EditText priceEdit;

    private EditText qtdEdit;

    private Button shootPhotoButton;

    private Button loadPhotoButton;

    private Button confirmButton;

    private Bitmap photoPrd;

    private String mCurrentPhotoPath;

    private TextView photoTextView;

    static final int REQUEST_TAKE_PHOTO = 1;

    private DatabaseHandler db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_update_product);
        
        
        
        db = new DatabaseHandler(getApplicationContext());
        photoPrd = null;
        mCurrentPhotoPath = null;
        nameEdit = (EditText) findViewById(R.id.manage_product_edit);
        descEdit = (EditText) findViewById(R.id.manage_description_edit);
        priceEdit = (EditText) findViewById(R.id.manage_unit_value_edit);
        qtdEdit = (EditText) findViewById(R.id.manage_stock_edit);
        photoTextView = (TextView) findViewById(R.id.manage_foto_product_text);
        shootPhotoButton = (Button) findViewById(R.id.manage_foto_edit);
        loadPhotoButton = (Button) findViewById(R.id.manage_load);
        confirmButton = (Button) findViewById(R.id.manage_button_update);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.update_user, menu);
        return true;
    }

    public void addProduct(View view) {
        String nameP = nameEdit.getText().toString();
        String descP = descEdit.getText().toString();
        int qtdP = Integer.valueOf(qtdEdit.getText().toString());
        Product product = new Product();
        product.setName(nameP);
        product.setDescription(descP);
        product.setQtdStock(qtdP);
        if (photoPrd != null) {
            product.setPhoto(photoPrd);
        }
        product.setUnitValue(Float.valueOf(priceEdit.getText().toString()));

        boolean teste = db.createProduct(product);

        Intent returnIntent = new Intent();
        returnIntent.putExtra("cadastro", teste);
        setResult(RESULT_OK, returnIntent);
        finish();

    }

    public void shootPhoto(View view) {
        dispatchTakePictureIntent();

        photoTextView.setText(mCurrentPhotoPath);
    }

    public void loadPhoto(View view) {
        Utils util = new Utils(this);
        int proportion = 6;
        int width = util.getWidthInPixels() / proportion;
        int height = util.getHeightInPixels() / proportion;
        if (mCurrentPhotoPath != null) {
            photoPrd = getResizedBitmap(BitmapFactory.decodeFile(mCurrentPhotoPath), width, height);

            ((ImageView) findViewById(R.id.manage_product_photo)).setImageBitmap(photoPrd);
        }

    }

    public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {

        int width = bm.getWidth();

        int height = bm.getHeight();

        float scaleWidth = ((float) newWidth) / width;

        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();

        matrix.postScale(scaleWidth, scaleHeight);
        matrix.postRotate(90.0f);

        Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);

        return resizedBitmap;

    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
                // ...
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            }
        }
    }

    @SuppressLint("SimpleDateFormat")
    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(imageFileName, /* prefix */
                ".jpg", /* suffix */
                storageDir /* directory */
        );
        // Save a file: path for use with ACTION_VIEW intents
        try {
            mCurrentPhotoPath = getPath(this, Uri.parse(image.toURI().toString()));

        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        // fotoU = BitmapFactory.decodeFile(path);
        // fotoTextView.setText("Foto: "+path);
        // Log.d(TAG, "File Path: " + path);

        System.out.println("!!!!!!!!!!!!!!!!!!" + mCurrentPhotoPath);
        return image;
    }

    public static String getPath(Context context, Uri uri) throws URISyntaxException {
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {
                "_data"
            };
            Cursor cursor = null;

            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
                // Eat it
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

}
